<?php
/**
 * get_curl() GET POST请求函数
 *
 * @param string $url 请求地址
 * @param string $post Post参数
 * @param string $referer 伪造referer
 * @param string $cookie cookie参数
 * @param string $header 头请求信息
 * @param string $ua 伪造User-Agent
 * @param string $nobaody 返回http响应头
 *
 * @return string 字符串内容
 */
function get_curl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	$httpheader[] = "Accept:application/json";
	$httpheader[] = "Accept-Encoding:gzip,deflate,sdch";
	$httpheader[] = "Accept-Language:zh-CN,zh;q=0.8";
	$httpheader[] = "Connection:close";
	curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
	if ($post) {
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	}
	if ($header) {
		curl_setopt($ch, CURLOPT_HEADER, true);
	}
	if ($cookie) {
		curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	}
	if ($referer) {
		if ($referer == 1) {
			curl_setopt($ch, CURLOPT_REFERER, 1);
		} else {
			curl_setopt($ch, CURLOPT_REFERER, $referer);
		}
	}
	if ($ua) {
		curl_setopt($ch, CURLOPT_USERAGENT, $ua);
	} else {
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Linux; U; Android 4.0.4; es-mx; HTC_One_X Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0");
	}
	if ($nobaody) {
		curl_setopt($ch, CURLOPT_NOBODY, 1);
	}
	curl_setopt($ch, CURLOPT_ENCODING, "gzip");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$ret = curl_exec($ch);
	curl_close($ch);
	return $ret;
}

/**
 * saveSetting() 快速修改frame_config表值函数
 *
 * @param string $k  k记录名 
 * @param string $v  v记录值 (要修改的值)
 *
 * @return boolean 结果
 */
function saveSetting($k, $v) {
    global $DB;
    $v = addslashes($v);
    return $DB->query("REPLACE INTO " . DBQZ . "_config SET v='$v',k='$k'");
}

/**
 * msg() 利用javascript alert()实现快捷提示框
 *
 * @param string $content 提示内容
 * @param string $ret 跳转地址  填整数 1 则返回上一页
 *
 * @return string 执行html + js
 */
function msg($content, $ret) {
    if ($ret == 1) {
        $ret = "history.go(-1);</script>";
    } else {
        $ret = "window.location.href='" . $ret . "';</script>";
    }
    exit("<script language='javascript'>alert('$content');$ret</script>");
}

/**
 * iflogin() 判断登录状态
 *
 * @param string DBQZ.$cookie 要判断cooki值  必须携带数据库前段名 {DBQZ}
 *
 * @return boolean 结果
 */
function iflogin($cookie) {
	session_start();
	if(isset($_COOKIE[DBQZ . "_cookie"])&&time()>$_COOKIE[DBQZ . "_cookie"]+3600*24*14){
		return true;
	}else{
		return false;
	}
}

/**
 * getkm() 生成随机字符串
 * 
 * @param string $len 生成字符长度
 *
 * @return string 字符内容
 */
function getkm($len = 12){
	$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	$strlen = strlen($str);
	$randstr = "";
	for ($i = 0; $i < $len; $i++) {
		$randstr .= $str[mt_rand(0, $strlen - 1)];
	}
	return $randstr;
}

/**
 * real_ip() 获取当前请求者IP
 *
 * @return string IP
 */
function real_ip() {
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] AS $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    }
    return $ip;
}

/**
 * get_ip_city() 查询IP位置信息
 * 
 * @param string $ip 要查询ip
 *
 * @return string 地址或查询失败 false
 */
function get_ip_city($ip) {
    $url = 'http://ipaddr.cz88.net/data.php?ip=';
    @$city = characet(get_curl($url . $ip));
	$arr = explode('ShowIPAddr',$city);
	$strrep = str_replace('(','',$arr[1]);
	$strrep = str_replace(')','',$strrep);
	$strrep = str_replace("'",'',$strrep);
	$strrep = str_replace(";",'',$strrep);
	$arr = explode(',',$strrep);
    if ($arr[1]) {
		return $arr[1];
    }else{
		return false;
    }
}

/**
 * defense() 检查字符串防注入
 *
 * @param string $string 内容
 *
 * @return string 过滤处理后内容
 */
function defense($string, $force = 0, $strip = FALSE) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = defense($val, $force, $strip);
			}
		} else {
			$string = addslashes($strip ? stripslashes($string) : $string);
		}
	}
	return $string;
}

/**
 * diffBetweenTwoDays() 计算两个日期之间天数
 *
 * @param string $day1 日期1
 * @param string $day2 日期2
 *
 * @return int 天数
 */
function diffBetweenTwoDays ($day1, $day2){
	if($day1 >= $day2){
		return 0;
	}else{
		$second1 = strtotime(explode(' ',$day1)[0]);
		$second2 = strtotime(explode(' ',$day2)[0]); 
		if ($second1 < $second2) {
			$tmp = $second2;
			$second2 = $second1;
			$second1 = $tmp;
		  }
		  return ($second1 - $second2) / 86400;
	}
}

/**
 * characet() 将非UTF-8字符集的编码转为UTF-8
 * 
 * @param string $data 日期1
 *
 * @return string 内容
 */
function characet($data){
	if( !empty($data) ){
		$fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')) ;
		if( $fileType != 'UTF-8'){
			$data = mb_convert_encoding($data ,'utf-8' , $fileType);
		}
	}
	return $data;
}

/**
 * addlog() 插入操作日记到数据库
 * 
 * @param str $content 操作行为
 *
 * @return boolean 结果
 */
function addlog($content = '无'){
	global $DB;
	$ip = real_ip();
	$date = date("Y-m-d H:i:s");
	$sql = $DB->query("INSERT INTO `". DBQZ ."_log`(`content`,`ip`,`date`) VALUES ('{$content}','{$ip}','{$date}')");
	if($sql){
		return true;
	}else{
		return false;
	}
}

/**
 * send_mail() 发送邮件
 * 
 * @param str $to 收件邮箱
 * @param str $sub 邮件标题
 * @param str $msg 内容
 *
 * @return boolean 结果
 */
function send_mail($to, $sub, $msg) {
	global $conf;
	include_once ROOT.'includes/smtp.class.php';
	if($conf['mail_type']==1){ //普通发信
		$From = $conf['mail_name'];
		$Host = $conf['mail_stmp'];
		$Port = $conf['mail_port'];
		$SMTPAuth = 1;
		$Username = $conf['mail_name'];
		$Password = $conf['mail_pwd'];
		$Nickname = $conf['name'];  //发信方名称(默认取网站标题)
		$SSL = $conf['mail_port']==465?1:0;
		$mail = new SMTP($Host , $Port , $SMTPAuth , $Username , $Password , $SSL);
		$mail->att = array();
		if($mail->send($to , $From , $sub , $msg, $Nickname)) {
			return true;
		} else {
			return $mail->log;
		}
	}
}

/**
 * authcode() 字符串加密 & 解密
 * 
 * @param str $string 内容
 * @param str $operation 类型   DECODE=解密    ENCODE=加密
 * @param str $key 秘钥(解密用)
 * @param int $expiry
 *
 * @return boolean 结果
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key = md5($key ? $key : ENCRYPT_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);
	$result = '';
	$box = range(0, 255);
	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}
?>
